package br.com.foxline.atlasmobile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import br.com.foxline.atlasmobile.dao.AnnexDao;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Annex;
import br.com.foxline.atlasmobile.entities.Imovel;

public class CroquisActivity extends Activity {

	private String ALBUMNAME = "atlasmobile";
	private static String IMOVEL = "getimovel";
	private static String PASTE_NAME = "";

	private ImovelDao imovelDao;
	private AnnexDao annexDao;
	private Imovel imovel;
	private ImageView image;
	private boolean createimage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_croquis);
		
		getActionBar().setTitle("CROQUI TERRENO");
		
		createimage = false;

		imovelDao = new ImovelDao(getApplicationContext());
		annexDao = new AnnexDao(getApplicationContext());
		
		image = (ImageView) findViewById(R.id.image_croqui);
		
		if (getIntent().getSerializableExtra(IMOVEL) != null) {
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);
			resgateImage();
		} else {
			imovel = new Imovel();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_croquis, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.btn_add_croqui:
			PackageManager packageManager = this.getPackageManager();
			Intent intent = packageManager
					.getLaunchIntentForPackage("air.GenbaTools.AngleShape");
			createimage = true;
			startActivity(intent);
			
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void save(){
		imovelDao.update(imovel);
	}
	
	public void next(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				CroquiImovelActivity.class);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_right,
				R.anim.slide_out_left);
		finish();
	}

	public void previous(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				InfoGeralActivity.class);
		intent.putExtra("last", true);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {

		if (createimage) {
			
			File file = new File(Environment
					.getExternalStoragePublicDirectory(
							Environment.DIRECTORY_DCIM).getParentFile()
					.toString()
					+ File.separator + "AngleShape" + File.separator);

			File f = null;

			if (file.listFiles().length <= 0) {
				super.onResume();
				return;
			}

			f = file.listFiles()[file.listFiles().length - 1];
			File dst = null;
			try {
				dst = createImageFile();
				copy(f, dst);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			

			Annex croquiTerreno = new Annex("CROQUI-TERRENO-IMOVEL-"
					+ imovel.getId(), "CROQUI TERRENO", "", Uri.fromFile(dst)
					.toString(), null, new Date(), "", ".JPG", imovel);
			
			annexDao.create(croquiTerreno);
			
			imovel.setCroquiTerreno(croquiTerreno);
			
			save();
			
		}
		
		resgateImage();

		super.onResume();
	}
	
	private void resgateImage(){
		if(image != null && imovel.getCroquiTerreno() != null && imovel.getCroquiTerreno().getUri() != null) {
			image.setImageURI(Uri.parse(imovel.getCroquiTerreno().getUri()));
		}
	}

	private File createImageFile() throws IOException {

		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyyMMdd_HHmmss");

		String timeStamp = simpleDateFormat.format(date);
		String imageFileName = "IMG_" + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, ".jpg", albumF);

		Annex annex = new Annex();
		annex.setCreate_at(date);
		annex.setName(imageF.getName());
		annex.setType(".jpg");

		return imageF;
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = getAlbumStorageDir();

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name),
					"External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	public File getAlbumStorageDir() {
		PASTE_NAME = File.separator + "CROQUI_IMOVEL-" + imovel.getId();
		File file = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
						+ "/" + ALBUMNAME + "/" + PASTE_NAME + "/");

		return file;
	}

	public void copy(File src, File dst) throws IOException {
		InputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dst);

		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
	}

}
